#!/usr/bin/env python3
import tkinter
from tkinter import ttk
import json

win = tkinter.Tk()
win.title("卷烟进价表")
win.geometry("650x770")

def treeview_sort_column(tv, col, reverse):
    l = [(tv.set(k, col), k) for k in tv.get_children('')]
    try:
        l.sort(key=lambda t: int(t[0]), reverse=reverse)
    except:
        l.sort(reverse=reverse)
    for index, (val, k) in enumerate(l):
        tv.move(k, '', index)
    tv.heading(col, command=lambda: treeview_sort_column(tv, col, not reverse))

with open('./cgtList221015.json', 'r', encoding='utf-8') as cgtdata:
    cgtdata_json = json.load(cgtdata)

tree = ttk.Treeview(win, show="headings", height=45)
columns = {'ID': {'width': 50, 'anchor': 'w'}, '名称': {'width': 200, 'anchor': 'w'}, '进价': {'width': 80, 'anchor': 'e'},
           '零售': {'width': 80, 'anchor': 'e'}, '盒码': {'width': 115, 'anchor': 'e'}, '条码': {'width': 115, 'anchor': 'e'}}
tree['columns'] = list(columns)

for column in columns:
    tree.heading(column, text=column,)
    tree.column(column, width=columns[column]['width'], anchor=columns[column]['anchor'])
    tree.heading(column, command=lambda _col=column: treeview_sort_column(tree, _col, False))

result = 0
for cgt in cgtdata_json:
    result += 1
    tree.insert('', 1000, text='', values=[result, cgt['CGT_NAME'], int(cgt['PRICE']),
                                           int(cgt['RTL_PRICE']), cgt['CGT_PACKET_CODE'], cgt['CGT_CARTON_CODE']])

tree.pack()
win.mainloop()
